package com.nowcoder.Offer.List;

import org.junit.Test;

/**
 * 合并两个排序链表
 */
public class MegreTwoList {

    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null ) return list2;
        if(list2 == null) return list1;
        ListNode p1 = list1, p2 = list2;
        ListNode head = new ListNode(-1);
        ListNode res = head;
        while(p1!=null && p2!=null){
            if(p1.val > p2.val){
                head.next = p2;
                head = head.next;
                p2 = p2.next;
            }else {
                head.next = p1;
                head = head.next;
                p1 = p1.next;
            }
        }

        head.next = p1 == null ? p2 : p1;
        return res.next;
    }

    @Test
    public void test(){
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(6);

        node1.next = node3;
        node3.next = node5;

        node2.next = node4;
        node4.next = node6;

        ListNode res = Merge(node1,node2);
        while(res!=null){
            System.out.println(res.val);
            res = res.next;
        }
    }

}
